import axios from "axios";
import store from "@/store";
import Storage from "@/utils/storageUtils"
import {Message} from "element-ui"
import router from "@/router";

axios.interceptors.request.use(config => {
  if (store.getters.getToken) {
    // 设置请求头
    config.headers.Authorization = store.getters.getToken ? store.getters.getToken : Storage.Local.get("token");
  }
  return config;
});

axios.interceptors.response.use(res => {
  if (res.data.code != 200 && res.data.code != 417) {
    Message({
      message: res.data.message,
      type: "error"
    });
  }
  return res;
}, error => {
  console.log(error.response)
  if (error.response.data.code == 401) {
    Message({
      message: error.response.data.message,
      type: "error"
    });
    router.push({
      path: "/login",
      name: "Login"
    });
    store.commit('setUserInfo', null);
    store.commit('setToken', null);
    return;
  }
});

export default {
  axios,
  get(url, params) {
    return axios({
      method: "GET",
      url,
      params,
      headers: {
        'content-type': 'application/json;charset=utf-8'
      }
    })
  },
  post(url, data) {
    return axios({
      method: "POST",
      url,
      data,
      headers: {
        'content-type': 'application/json;charset=utf-8'
      }
    })
  },
  put(url, data) {
    return axios({
      method: "PUT",
      url,
      data,
      headers: {
        'content-type': 'application/json;charset=utf-8'
      }
    })
  },
  delete(url, params) {
    return axios({
      method: "DELETE",
      url,
      params,
      headers: {
        'content-type': 'application/json;charset=utf-8'
      }
    })
  }
}
